package com.purchase.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.purchase.jd.commodity.JdConstants;
import com.purchase.jd.http.HttpHeaders;
import com.purchase.jd.http.JdHttpUtil;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @author saw
 */
public class JudgeUtils {

    /**
     * 京东获取抢购时间
     * @throws IOException
     */
    public static long getJdPurchaseTime(){
        //获取开始时间
        Map<String,String> headers = HttpHeaders.getHeaders();
        //获取商品信息
        String shopDetail = HttpUtils.get(headers, JdConstants.COMMODITY_URL+JdConstants.SKU_ID).body();
        JSONObject jsonObject = JSON.parseObject(shopDetail);
        if(null == jsonObject.get("yuyueInfo")){
            throw new RuntimeException("商品不存在，请更换skuId再试");
        }
        //获取抢购时间
        String buyDate = JSONObject.parseObject(jsonObject.getString("yuyueInfo"))
                //秒杀方法是miaoshaInfo
                .getString("buyTime");
        String startDate = buyDate.split("-202")[0] + ":00";
        System.out.println("商品抢购时间："+startDate);
        long startTime = DateUtils.dateStrToTime(startDate);
        //获取京东时间
        String jdTime = HttpUtils.get(headers, JdConstants.TIME_URL).body();
        long serverTime = Long.parseLong(JSONObject.parseObject(jdTime).getString(JdConstants.TIME_COLUMN));
        System.out.println("当前京东时间："+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date(serverTime)));
        //获取多少秒后开启线程
        return startTime-serverTime-100>0?startTime-serverTime-100:0;
    }

    /**
     * 京东获取秒杀时间
     * @throws IOException
     */
    public static long getJdSpikeTime(){
        //获取开始时间
        Map<String,String> headers = HttpHeaders.getHeaders();
        //获取商品信息
        String shopDetail = HttpUtils.get(headers, JdConstants.COMMODITY_URL+JdConstants.SKU_ID).body();
        JSONObject jsonObject = JSON.parseObject(shopDetail);
        if(null == jsonObject.get("miaoshaInfo")){
            throw new RuntimeException("商品不存在，请更换skuId再试");
        }
        //获取抢购时间
        long startTime = JSONObject.parseObject(jsonObject.getString("miaoshaInfo"))
                .getLong("startTime");
        System.out.println("商品秒杀时间："+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date(startTime)));
        //获取京东时间
        String jdTime = HttpUtils.get(headers, JdConstants.TIME_URL).body();

        long serverTime = Long.parseLong(JSONObject.parseObject(jdTime).getString(JdConstants.TIME_COLUMN));
        System.out.println("当前京东时间："+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date(serverTime)));
        //获取多少秒后开启线程  因为有三个请求，考虑到延迟，提前300毫秒
        return startTime-serverTime-300>0?startTime-serverTime-300:0;
    }
}
